package com.gzz.orchid.common.core.authorization;

import java.util.Optional;

/**
 * 授权用户上下文
 * 本地线程上下文()
 *
 * @author higmd
 */
public class UserContextHolder {
    public static ThreadLocal<AuthorizedUser> context = new ThreadLocal<>();

    /**
     * 获取当前登录用户
     */
    public static AuthorizedUser currentUser() {
        return Optional.ofNullable(context.get())
                // 抛出 -> 获取不到当前登录用户信息
                .orElseThrow(() -> new RuntimeException("Unable to obtain current login user information"));
    }

    /**
     * 获取当前登录用户
     */
    public static Optional<AuthorizedUser> getAuthorizedUser() {
        return Optional.ofNullable(context.get());
    }

    /**
     * 设置当前登录用户
     */
    public static void set(AuthorizedUser user) {
        context.set(user);
    }

    /**
     * 移除当前登录用户
     */
    public static void remove() {
        context.remove();
    }

    /**
     * 获取特权
     */
    public static boolean getPrivilege() {
        return Optional.ofNullable(context.get())
                .map(item -> !item.isSuper())
                .orElse(Boolean.FALSE);
    }

    /**
     * 获取当前登录用户名称
     */
    public static String getUserName() {
        return Optional.ofNullable(context.get())
                .map(AuthorizedUser::getUserName)
                .orElse("");
    }

    /**
     * 获取当前登录用户编码
     */
    public static String getUserCode() {
        return Optional.ofNullable(context.get())
                .map(AuthorizedUser::getUserCode)
                .orElse("");
    }
}
